package com.gosling.cloudspace.config.mybatis;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import net.sf.jsqlparser.expression.Alias;
import net.sf.jsqlparser.schema.Column;
import net.sf.jsqlparser.schema.Table;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * MyBatis 工具类
 */
public class MyBatisUtils {

    private static final String MYSQL_ESCAPE_CHARACTER = "`";

    public static <T> Page<T> buildPage(PageParam pageParam) {
        return buildPage(pageParam, null);
    }

    public static <T> Page<T> buildPage(PageParam pageParam, Collection<SortingField> sortingFields) {
        // 页码 + 数量
        Page<T> page = new Page<>(pageParam.getPageNo(), pageParam.getPageSize());
        // 排序字段
        if (!CollectionUtil.isEmpty(sortingFields)) {
            page.addOrder(sortingFields.stream().map(sortingField -> SortingField.ORDER_ASC.equals(sortingField.getOrder()) ?
                            OrderItem.asc(sortingField.getField()) : OrderItem.desc(sortingField.getField()))
                    .collect(Collectors.toList()));
        }
        return page;
    }

    /**
     * 将拦截器添加到链中
     * 由于 MybatisPlusInterceptor 不支持添加拦截器，所以只能全量设置
     *
     * @param interceptor 链
     * @param inner       拦截器
     * @param index       位置
     */
    public static void addInterceptor(MybatisPlusInterceptor interceptor, InnerInterceptor inner, int index) {
        List<InnerInterceptor> inners = new ArrayList<>(interceptor.getInterceptors());
        inners.add(index, inner);
        interceptor.setInterceptors(inners);
    }

    /**
     * 获得 Table 对应的表名
     * <p>
     * 兼容 MySQL 转义表名 `t_xxx`
     *
     * @param table 表
     * @return 去除转移字符后的表名
     */
    public static String getTableName(Table table) {
        String tableName = table.getName();
        if (tableName.startsWith(MYSQL_ESCAPE_CHARACTER) && tableName.endsWith(MYSQL_ESCAPE_CHARACTER)) {
            tableName = tableName.substring(1, tableName.length() - 1);
        }
        return tableName;
    }

    /**
     * 构建 Column 对象
     *
     * @param tableName  表名
     * @param tableAlias 别名
     * @param column     字段名
     * @return Column 对象
     */
    public static Column buildColumn(String tableName, Alias tableAlias, String column) {
        if (tableAlias != null) {
            tableName = tableAlias.getName();
        }
        return new Column(tableName + StringPool.DOT + column);
    }

    /***
     * 批量执行，一次会话执行
     *
     * @param list
     */
    public static <T> void addBatch(List<T> list, BaseMapperX<T> mapperX, SqlSessionFactory ssf) {
        //创建批量任务执行的会话
        SqlSession sqlSession = ssf.openSession(ExecutorType.BATCH, false);
        BaseMapperX<T> mapper = sqlSession.getMapper(mapperX.getClass());
        try {
            if (CollectionUtil.isNotEmpty(list)) {
                list.forEach(e -> mapper.insert(e));
            }
        } finally {
            //批量执行完成必须手动提交事务和清理缓存
            sqlSession.commit();
            sqlSession.clearCache();
        }
    }

    /**
     * mybatis查询时时间格式处理-00:00:00
     *
     * @param beginDate
     * @return
     */
    public static LocalDateTime dateBegin(LocalDate beginDate) {
        return LocalDateTime.of(beginDate.getYear(), beginDate.getMonth(), beginDate.getDayOfMonth(), 0, 0, 0);
    }

    public static String dateBegin(String beginDate) {
        return beginDate + " 00:00:00";
    }

    /**
     * mybatis查询时时间格式处理-23:59:59
     *
     * @param beginDate
     * @return
     */
    public static LocalDateTime dateEnd(LocalDate beginDate) {
        return LocalDateTime.of(beginDate.getYear(), beginDate.getMonth(), beginDate.getDayOfMonth(), 23, 59, 59);
    }

    public static String dateEnd(String beginDate) {
        return beginDate + " 23:59:59";
    }

    /***
     * 将id集合转换为sql in语句 直接进行拼接
     * @param ids
     * @return
     */
    public static String sqlInToString(List<String> ids) {
        String join = String.join("','", ids);
        return "'" + join + "'";
    }

    public static String sqlInToString(Set<String> ids) {
        return sqlInToString(new ArrayList<>(ids));
    }

}
